package cn.song.service.impl;

import cn.song.dto.OrderDto;
import cn.song.enums.ResultEnum;
import cn.song.exceptions.SellException;
import cn.song.service.BuyerService;
import cn.song.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class BuyerServiceImpl implements BuyerService {

    @Autowired
    private OrderService orderService;

    @Override
    public OrderDto findOrderOne(String openid, String orderId) {

        OrderDto orderDto = checkOwnOrder(openid, orderId);
        return orderDto;
    }

    @Override
    public OrderDto cancelOrder(String openid, String orderId) {
        OrderDto orderDto = checkOwnOrder(openid, orderId);
        if(orderDto==null){
            log.error("查询订单不存在 ,orderId  is {}.",orderId);
            throw new SellException(ResultEnum.OPENID_IS_NOT_EXIST);
        }
        return orderService.Cannel(orderDto);
    }



    private OrderDto checkOwnOrder(String openid, String orderId){
        OrderDto order = orderService.findOne(orderId);
        if(order==null){
            return  null;
        }
        if(!order.getBuyerOpenid().equals(openid)){
            log.error("查询订单openid不一致, opnid is {}. orderDto is {}.",openid, order);
            throw new SellException(ResultEnum.OPENID_IS_SAME);
        }
        return order;
    }
}
